1672D - Cyclic Rotation - CodeForces Solution


constructive algorithms greedy implementation two pointers *1700

Please click on ads to support us..

Python Code:

    
    
        
        
    
    

            
def ss(a,b):
    d={i:0 for i in b}

            if a[-1]!=b[-1]:
        return "NO"
    n=len(a)
    i=n-1
    j=n-1
    
    while i>=0 and j>=0:
        while j>=1  and b[j]==b[j-1]:
            x=b[j]
            d[x]+=1
            j-=1  
        
        if a[i]==b[j]:
            i-=1 
            j-=1 
            
        
        elif d[a[i]]>0:
            x=a[i]
            i-=1 
            d[x]-=1 
        else:
            return "NO"
    
    return "YES"


    
    
import collections


def transform(a, b):
    counter = collections.Counter()
    while a:
        while len(b) > 1 and b[-1] == b[-2]:
            counter[b.pop()] += 1
        if b and a[-1] == b[-1]:
            a.pop()
            b.pop()
        elif counter[a[-1]]:
            counter[a.pop()] -= 1
        else:
            return False
    return True


for _ in range(int(input())):
    input()
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    print("YES" if transform(a, b) else "NO")

C++ Code:

#include<bits/stdc++.h>
#define MOD 1000000007
#define MAX 200000
using namespace std;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t;
	cin>>t;
	int cnt = 0;
	while(t--)
	{
		int n;
		cin>>n;
		vector<int> a(n),b(n);
		for(int &x:a)cin>>x;
		for(int &x:b)cin>>x;
		bool ok = 1;
		multiset<int> st;
		for(int i=0,j=0,last=0;ok&&j<n;)
		{
			if(i<n&&a[i]==b[j])
				j++, last = a[i++];
			else if(last==b[j]&&st.find(b[j])!=st.end())	
				st.erase(st.find(b[j++]));
			else if(i<n)
				st.insert(a[i++]);
			else ok = 0;
		}
		if(ok)
			cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number